package jobs.job3.classloaderdemo.server.util;

import java.io.*;
import java.util.Arrays;
import java.util.Random;

public class Utils {
    public static int[] genUnorderedArray(int len) {
        int[] array = new int[len];//0,0,0,0,0,0,0,...
        Arrays.setAll(array, i -> i);//0,1,2,3,4,5,6,7,...
        shuffle(array);
        return array;
    }

    private static void shuffle(int[] array) {
        Random random = new Random();
        for (int i = 0; i < array.length - 1; i++) {
            int j = random.nextInt(array.length - i - 1) + i + 1;
            array[i] ^= array[j];//交换2个元素的值
            array[j] ^= array[i];
            array[i] ^= array[j];
        }
    }

    public static byte[] convertToBytes(Object obj) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(buffer);
        objectOutputStream.writeObject(obj);
        byte[] bytes = buffer.toByteArray();
        objectOutputStream.close();
        buffer.close();
        return bytes;
    }

    public static <T> T bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        //noinspection unchecked
        T array = (T) objectInputStream.readObject();
        objectInputStream.close();
        return array;
    }

}
